package ProjectTeam39.Networking;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import java.net.Socket;
import java.net.SocketException;

public class MessageHandler implements Runnable {
    /** the socket for the client */
    private Socket mySocket;
    /** the model */
    private Model theModel;

    /**
     * Creates a new ClientMessageHandler object.
     *
     * @param sock the socket made by the accept
     * @param model a reference to the backend
     */
    public MessageHandler(final Socket sock, final Model model) {
        mySocket = sock;
    }

    /**
     * Overidden Method
     *
     * @see java.lang.Runnable#run()
     */
    public void run() {
        ObjectInputStream  inStream;
       ObjectOutputStream outStream;
        System.out.println("Connection from "
            + mySocket.getInetAddress().getHostName());

        boolean notDone = true;

        try {
            //always make the output stream first and flush
            outStream = new ObjectOutputStream(mySocket.getOutputStream());
            outStream.flush();
            System.err.println("Made server outstream");
            //then make the input stream
            inStream = new ObjectInputStream(
                        mySocket.getInputStream());
            System.err.println("Made server instream");

            while (notDone) {
                Message mess = (Message) inStream.readUnshared();
                System.err.println("Got server message");

                if (!(mess instanceof QuitMessage)) {
                    Message result = mess.handle(theModel);
                    outStream.writeUnshared(result);
                    outStream.flush();
                    System.err.println("Sent server message");
                } else {
                    inStream.close();
                    outStream.close();
                    mySocket.close();
                    notDone = false;
                   System.out.println("Connection Closed");
                }
            }
        } catch (SocketException se) {
            System.err.println("Detected Client Disconnect");
        } catch (IOException e) {
            System.err.println(
                "Error in client handler, could not establish streams or "
                 +  " there was a disconnect");
        } catch (ClassNotFoundException cnfe) {
            System.err.println("Could not find message class");
        }
    }
}
